import http from './http'

const globalDownloadUrl = ''

export function $asPost(url, data, contentType) {
    const ct = contentType || 'application/json;charset=UTF-8'
    let str = '?'
    for (const key in data) {
        str += key + '=' + data[key] + '&'
    }
    str = str.replace(/&$/gi, '')
    return http({
        method: 'post',
        url: url + str,
        headers: { 'Content-Type': ct }
    })
}

export function $post(url, data, contentType, config = {}) {
    const ct = contentType || 'application/json;charset=UTF-8'
    return http({
        method: 'post',
        url: url,
        data: data,
        headers: { 'Content-Type': ct },
        ...config
    })
}

export function $uploadPost(url, data, config = {}) {
    return http({
        method: 'post',
        url: url,
        data: data,
        ...config
    })
}
export function $uploadGet(url, data, config = {}) {
    for (const key in data) {
        data[key] = encodeURI(data[key])
    }
    return http({
        method: 'get',
        url: url,
        params: data,
        ...config
    })
}
export function $get(url, data, contentType) {
    const ct = contentType || 'application/x-www-form-urlencoded;charset=UTF-8'
    data = data || {}
    return http({
        method: 'get',
        url: url,
        params: data,
        headers: {
            'Content-Type': ct
        }
    })
}

export function $getBlob(url, data, contentType) {
    const ct = contentType || 'application/x-www-form-urlencoded;charset=UTF-8'
    data = data || {}
    for (const key in data) {
        data[key] = encodeURI(data[key])
    }
    return http({
        method: 'get',
        url: url,
        params: data,
        responseType: 'blob',
        headers: {
            'Content-Type': ct
        }
    })
}

export function $downloadFile(blob) {
    if (!blob) {
        alert('链接为空，请检查！')
        return
    } else {
        blob = globalDownloadUrl + blob.substring(0, blob.lastIndexOf('.'))
    }
    window.open(blob)
}